package com.hg.hggood.service.impl;

import com.hg.hggood.entity.Address;
import com.hg.hggood.entity.Order;
import com.hg.hggood.entity.OrderItem;
import com.hg.hggood.mapper.OrderMapper;
import com.hg.hggood.service.IAddressService;
import com.hg.hggood.service.ICartService;
import com.hg.hggood.service.IOrderService;
import com.hg.hggood.service.IUserService;
import com.hg.hggood.service.ex.*;
import com.hg.hggood.vo.CartVO;
import com.hg.hggood.vo.OrderVO;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IUserService userService;

    @Override
    public Order create(Integer aid, Integer uid, String username, Integer[] cids) {
        //即将要下订单的列表
        List<CartVO> list = cartService.getVOByCid(uid, cids);
        //计算产品的总价
        Double totalPrice = Double.valueOf(0L);

        for (CartVO c: list) {                  //我打了六折
            totalPrice +=  c.getRealprice() * c.getNum() * 0.6;
        }

        Address address = addressService.getByAid(aid, uid);
        Order order = new Order();
        order.setUid(uid);

        String hexStr = UUID.randomUUID().toString().toUpperCase().replace("-","").trim().replaceAll("(.{4})", "$1 ");
        Integer intnum = 0;
        String strnum="";
        for(int i=10;i<25; i=i+5){      //i一共可从0-40取
            intnum = Integer.parseInt(hexStr.substring(i,i+4),16);
            strnum += intnum.toString();
        }   //通过uuid生成订单号
        order.setOnum(strnum);

        //收货地址数据
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        //支付、总价
        order.setStatus(0);
        order.setTotalPrice(totalPrice);
        order.setOrderTime(new Date());
        //日志
        order.setCreatedUser(username);
        order.setCreatedTime(new Date());
        order.setModifiedUser(username);
        order.setModifiedTime(new Date());
        //查询数据
        Integer rows = orderMapper.insertOrder(order);
        if (rows != 1){
            throw new InsertException("插入数据异常");
        }

        //创建订单详情项的数据
        for (CartVO c: list){
            //创建一个订单项数据对象
            OrderItem orderItem = new OrderItem();
            orderItem.setOid(order.getOid());
            orderItem.setPid(c.getPid());
            orderItem.setTitle(c.getTitle());
            orderItem.setImage(c.getImage());
            orderItem.setPrice(c.getRealprice());
            orderItem.setNum(c.getNum());
            //日志字段
            orderItem.setCreatedUser(username);
            orderItem.setCreatedTime(new Date());
            orderItem.setModifiedUser(username);
            orderItem.setModifiedTime(new Date());
            //插入数据操作
            rows = orderMapper.insertOrderItem(orderItem);
            if (rows != 1){
                throw new InsertException("插入数据异常");
            }
//            orderMapper.insertOrderItem(orderItem);
        }
        return order;
    }


    @Override
    public List<OrderVO> getVOByUid(Integer uid) {
        return orderMapper.findVOByUid(uid);
    }

    @Override
    public void delete(Integer oid, Integer uid, String username) {
        Order result = orderMapper.findByOid(oid);
        if (result == null){
            throw new OrderNotFoundException("该订单序号不存在的异常");
        }
//        检测当前获取到的收货地址数据的归属
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }
        Integer rows = orderMapper.deleteByOid(oid);
        System.out.println(rows+"###");
        if ( rows < 2){
            throw new DeleteException("删除数据产生未知的异常");
        }
        Integer count = orderMapper.countByUid(uid);
        if ( count == 0){
            //直接终止程序
            return;
        }
    }

    @Override
    public void deleteOrderItemId(Integer id , Integer uid, String username) {
        OrderItem result = orderMapper.findItemById(id);
        if (result == null){
            throw new OrderItemNotFoundException("该订单详情序号不存在的异常");
        }
        Order result2 = orderMapper.findByOid(result.getOid());
        //检测当前获取到的收货地址数据的归属
        if (!result2.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据访问");
        }
        Integer rows = orderMapper.deleteById(id);
        if ( rows != 1){
            throw new DeleteException("删除订单详情数据产生未知的异常");
        }
        Integer oid = result.getOid();
        Integer count = orderMapper.countByOid(oid);
        System.out.println("count="+count+"%%%");
        //如果还有三个订单详情id则count返回2,如果有两个则返回1,一个返回0
        //这里的计算是由删完之后计算出来的订单详情id的数量
        if (count == 0){
            Integer rows2 = orderMapper.deleteByOid(oid);
            //这里显示的行数和上面用同样方法显示的行数不一样
            //因为此时的受影响行数是在上处删完之后需要减1
            //这里的通过oid删除是纯粹的删除t_order里边的oid
            System.out.println("rows2="+rows2+"###");
            if ( rows2 != 1){
                throw new DeleteException("删除订单数据产生未知的异常");
            }
        }else if (count >0){
            Double totalprice = result2.getTotalPrice()-result.getNum()*result.getPrice()*0.6;
            String username2 = userService.getByUid(result2.getUid()).getUsername();
            Integer rows3 = orderMapper.updateTotalPriceByOid(oid,totalprice,username2,new Date());
            if ( rows3 != 1){
                throw new UpdateException("更新数据时产生未知的异常");
            }
        }
    }
}
